const express = require('express');
const cors = require('cors');
const { v4: uuidv4 } = require('uuid');
const path = require('path');
const LLMService = require('./llm-service');
const { chromium } = require('playwright');

// 创建Express应用
const app = express();
const PORT = process.env.AGENT_PORT || 5001;

// 中间件
app.use(cors());
app.use(express.json());

// 存储用户会话
const sessions = new Map();

// 初始化LLM服务
const llmService = new LLMService();

// 增强的命令解析器
class CommandParser {
  constructor() {
    // 支持的命令模式
    this.commandPatterns = [
      {
        name: 'createTask',
        pattern: /创建(.*?)任务给(.*?)$/i,
        extract: (matches) => ({
          type: 'createTask',
          title: matches[1].trim(),
          recipient: matches[2].trim()
        })
      },
      {
        name: 'listTasks',
        pattern: /查看(.*?)的任务/i,
        extract: (matches) => ({
          type: 'listTasks',
          user: matches[1].trim()
        })
      },
      {
        name: 'help',
        pattern: /帮助|使用说明|怎么用/i,
        extract: () => ({
          type: 'help'
        })
      }
    ];
  }

  // 解析用户命令
  parse(command) {
    for (const pattern of this.commandPatterns) {
      const matches = command.match(pattern.pattern);
      if (matches) {
        return pattern.extract(matches);
      }
    }

    // 如果没有匹配的模式，尝试理解为创建任务命令
    return this.fallbackParse(command);
  }

  // 回退解析策略
  fallbackParse(command) {
    // 提取可能的任务标题和接收者
    // 简单的关键词匹配
    if (command.includes('任务')) {
      const taskIndex = command.indexOf('任务');
      let title = command.substring(0, taskIndex).replace(/创建|新建|添加|生成|发起|发布/i, '').trim();
      let recipient = command.substring(taskIndex).replace(/任务|给|分配给|发送给|交给/i, '').trim();

      return {
        type: 'createTask',
        title: title || '任务',
        recipient: recipient
      };
    }

    return { type: 'unknown', command };
  }
}

const commandParser = new CommandParser();

// 创建新的会话
app.post('/api/agent/sessions', async (req, res) => {
  try {
    const sessionId = uuidv4();
    const userInfo = req.body;

    // 创建新的浏览器上下文 - 可视化模式
    const browser = await chromium.launch({
      headless: false,  // 显示浏览器窗口
      slowMo: 1000,     // 操作间隔1秒，便于观察
      args: [
        '--start-maximized',  // 最大化窗口
        '--no-sandbox',
        '--disable-dev-shm-usage'
      ]
    });

    const context = await browser.newContext({
      viewport: { width: 1920, height: 1080 },  // 设置窗口大小
      userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
    });

    const page = await context.newPage();

    // 保存会话信息
    sessions.set(sessionId, {
      id: sessionId,
      userInfo,
      browser,
      context,
      page,
      createdAt: Date.now()
    });

    res.status(201).json({
      sessionId,
      message: 'Agent session created successfully'
    });
  } catch (error) {
    console.error('Failed to create agent session:', error);
    res.status(500).json({ error: 'Failed to create agent session' });
  }
});

// 获取页面DOM信息
async function getPageDOMInfo(page) {
  try {
    const domInfo = await page.evaluate(() => {
      // 获取所有可交互元素
      const interactiveElements = [];

      // 查找各种类型的可交互元素
      const selectors = [
        'input', 'button', 'select', 'textarea', 'a',
        '[onclick]', '[role="button"]', '[tabindex]',
        '.btn', '.button', '.link', '.nav-item'
      ];

      selectors.forEach(selector => {
        const elements = document.querySelectorAll(selector);
        elements.forEach((el, index) => {
          if (el.offsetParent !== null) { // 只获取可见元素
            const rect = el.getBoundingClientRect();
            interactiveElements.push({
              tagName: el.tagName.toLowerCase(),
              type: el.type || 'unknown',
              id: el.id || '',
              className: el.className || '',
              text: el.textContent?.trim().substring(0, 100) || '',
              placeholder: el.placeholder || '',
              name: el.name || '',
              value: el.value || '',
              href: el.href || '',
              selector: `${el.tagName.toLowerCase()}${el.id ? '#' + el.id : ''}${el.className ? '.' + el.className.split(' ').join('.') : ''}`,
              position: {
                x: Math.round(rect.x),
                y: Math.round(rect.y),
                width: Math.round(rect.width),
                height: Math.round(rect.height)
              },
              index: index
            });
          }
        });
      });

      // 获取页面基本信息
      return {
        title: document.title,
        url: window.location.href,
        pathname: window.location.pathname,
        search: window.location.search,
        hash: window.location.hash,
        bodyText: document.body.innerText.substring(0, 2000),
        interactiveElements: interactiveElements,
        forms: Array.from(document.forms).map(form => ({
          id: form.id,
          name: form.name,
          action: form.action,
          method: form.method,
          elements: Array.from(form.elements).map(el => ({
            name: el.name,
            type: el.type,
            value: el.value,
            required: el.required
          }))
        })),
        headings: Array.from(document.querySelectorAll('h1, h2, h3, h4, h5, h6')).map(h => ({
          level: parseInt(h.tagName.substring(1)),
          text: h.textContent.trim()
        })),
        timestamp: new Date().toISOString()
      };
    });

    return domInfo;
  } catch (error) {
    console.error('获取DOM信息失败:', error);
    return null;
  }
}

// 解析命令并执行
async function executeCommand(session, command, domInfo = null, pageContext = null) {
  try {
    const { page, userInfo } = session;

    // 如果页面还未导航，导航到默认页面
    if (page.url() === 'about:blank') {
      await page.goto('http://localhost:3000', { waitUntil: 'networkidle' });
    }

    // 获取当前页面的DOM信息
    let currentDOMInfo = null;
    try {
      currentDOMInfo = await getPageDOMInfo(page);
    } catch (error) {
      console.warn('获取当前页面DOM信息失败:', error.message);
    }

    // 合并前端传递的DOM信息和当前获取的信息
    const enhancedDOMInfo = {
      ...currentDOMInfo,
      frontendData: domInfo,
      pageContext: pageContext
    };

    // 构建页面信息对象供LLM分析
    const pageInfo = {
      url: enhancedDOMInfo.url || (domInfo ? domInfo.url : ''),
      title: enhancedDOMInfo.title || (domInfo ? domInfo.title : ''),
      content: enhancedDOMInfo.bodyText || (domInfo ? domInfo.bodyText : ''),
      domInfo: enhancedDOMInfo,
      pageContext: pageContext
    };

    // 使用LLM分析用户指令和页面内容
    let llmAnalysis = null;
    try {
      llmAnalysis = await llmService.analyzePage(pageInfo, command);
      console.log('LLM分析结果:', llmAnalysis);
    } catch (error) {
      console.warn('LLM分析失败，使用备用逻辑:', error.message);
    }

    // 使用增强的命令解析器
    const parsedCommand = commandParser.parse(command);

    // 判断是否为任务型指令
    const isTaskCommand = parsedCommand.type === 'createTask' ||
                         command.includes('创建') ||
                         command.includes('任务') ||
                         command.includes('点击') ||
                         command.includes('填写') ||
                         command.includes('操作');

    if (isTaskCommand) {
      // 执行具体的任务操作
      switch (parsedCommand.type) {
        case 'createTask':
          const result = await handleCreateTask(page, parsedCommand.title, parsedCommand.recipient);
          return {
            ...result,
            analysis: llmAnalysis,
            domInfo: enhancedDOMInfo,
            command: command
          };

        default:
          // 尝试基于LLM分析执行智能操作
          if (llmAnalysis && llmAnalysis.recommendedSteps && llmAnalysis.recommendedSteps.length > 0) {
            const operationResult = await executeIntelligentOperation(page, llmAnalysis, command);
            return {
              ...operationResult,
              analysis: llmAnalysis,
              domInfo: enhancedDOMInfo,
              command: command
            };
          } else {
            return {
              success: false,
              message: `我理解您想要: "${command}"\n\n但暂时无法确定具体的操作步骤。请尝试更具体的指令，比如：\n• 创建XX任务给XXX\n• 点击某个按钮\n• 填写某个表单`,
              analysis: llmAnalysis,
              domInfo: enhancedDOMInfo,
              command: command
            };
          }
      }
    } else {
      // 非任务型指令，仅进行分析和说明
      const analysisMessage = llmAnalysis ?
        (llmAnalysis.rawAnalysis || llmAnalysis.summary || '已完成页面分析') :
        '已分析当前页面内容';

      return {
        success: true,
        message: `${analysisMessage}\n\n📄 当前页面: ${enhancedDOMInfo.title || '未知'}\n🔗 页面链接: ${enhancedDOMInfo.url || '未知'}\n🎯 可交互元素: ${enhancedDOMInfo.interactiveElements?.length || 0} 个`,
        analysis: llmAnalysis,
        domInfo: enhancedDOMInfo,
        command: command
      };
    }
  } catch (error) {
    console.error('Command execution error:', error);
    return {
      success: false,
      message: '命令执行失败',
      error: error.message,
      command: command
    };
  }
}

// 执行智能操作
async function executeIntelligentOperation(page, analysis, originalCommand) {
  try {
    const steps = analysis.recommendedSteps || [];
    let executedSteps = [];

    for (const step of steps) {
      try {
        let stepResult = `步骤 ${step.step || executedSteps.length + 1}: ${step.action}`;

        switch (step.action.toLowerCase()) {
          case '点击':
          case 'click':
            if (step.selector) {
              await page.click(step.selector);
              stepResult += ` ✓`;
            }
            break;

          case '填写':
          case 'fill':
          case '输入':
            if (step.selector && step.value) {
              await page.fill(step.selector, step.value);
              stepResult += ` ✓`;
            }
            break;

          case '选择':
          case 'select':
            if (step.selector && step.value) {
              await page.selectOption(step.selector, step.value);
              stepResult += ` ✓`;
            }
            break;

          case '等待':
          case 'wait':
            if (step.selector) {
              await page.waitForSelector(step.selector, { timeout: 5000 });
              stepResult += ` ✓`;
            } else {
              await page.waitForTimeout(1000);
              stepResult += ` ✓`;
            }
            break;

          case '导航':
          case 'navigate':
          case '跳转':
            if (step.value) {
              await page.goto(step.value);
              stepResult += ` ✓`;
            }
            break;

          default:
            stepResult += ` (跳过 - 不支持的操作)`;
        }

        executedSteps.push(stepResult);

        // 等待页面稳定 - 增加延时便于观察
        await page.waitForTimeout(2000);

      } catch (stepError) {
        console.error(`执行步骤失败:`, stepError);
        executedSteps.push(`步骤 ${step.step || executedSteps.length + 1}: ${step.action} ✗ (${stepError.message})`);
      }
    }

    return {
      success: executedSteps.length > 0,
      message: `基于您的指令 "${originalCommand}"，我执行了以下操作:\n\n${executedSteps.join('\n')}\n\n操作完成！`,
      executedSteps: executedSteps
    };

  } catch (error) {
    console.error('智能操作执行失败:', error);
    return {
      success: false,
      message: `尝试执行智能操作时出错: ${error.message}`
    };
  }
}

// 处理创建任务命令
async function handleCreateTask(page, taskTitle, recipientName) {
  try {
    // 打开任务创建页面
    await page.goto('http://localhost:3000/notifications/create', {
      waitUntil: 'networkidle',
      timeout: 30000
    });

    // 等待页面加载完成
    await page.waitForSelector('select[name="recipientId"]', { timeout: 5000 });

    // 获取所有选项并查找匹配的接收者
    const optionTexts = await page.evaluate(() => {
      const select = document.querySelector('select[name="recipientId"]');
      if (!select) return [];
      return Array.from(select.options).map(option => option.textContent.trim());
    });

    // 查找匹配的接收者
    const matchingOption = optionTexts.find(option =>
      option.toLowerCase().includes(recipientName.toLowerCase())
    );

    if (!matchingOption) {
      return {
        success: false,
        message: `未找到名为"${recipientName}"的员工，请检查员工姓名是否正确`
      };
    }

    // 选择接收者
    await page.selectOption('select[name="recipientId"]', {
      label: matchingOption
    });

    // 填写任务标题
    await page.fill('input[name="title"]', taskTitle);

    // 填写任务内容
    await page.fill('textarea[name="content"]', `自动创建的任务: ${taskTitle}\n此任务由智能体助手自动创建`);

    // 提交表单并等待导航完成
    await Promise.all([
      page.click('button[type="submit"]'),
      page.waitForNavigation({ waitUntil: 'networkidle' })
    ]);

    return {
      success: true,
      message: `成功创建任务: "${taskTitle}" 给 "${matchingOption}"`
    };
  } catch (error) {
    console.error('Create task error:', error);
    throw error;
  }
}

// 执行命令
app.post('/api/agent/sessions/:sessionId/execute', async (req, res) => {
  try {
    const { sessionId } = req.params;
    const { command, domInfo, pageContext } = req.body;

    if (!sessions.has(sessionId)) {
      return res.status(404).json({ error: 'Session not found' });
    }

    const session = sessions.get(sessionId);
    const result = await executeCommand(session, command, domInfo, pageContext);

    res.json(result);
  } catch (error) {
    console.error('Failed to execute command:', error);
    res.status(500).json({ error: 'Failed to execute command', details: error.message });
  }
});

// 获取会话状态
app.get('/api/agent/sessions/:sessionId/status', (req, res) => {
  try {
    const { sessionId } = req.params;

    if (!sessions.has(sessionId)) {
      return res.status(404).json({ error: 'Session not found' });
    }

    const session = sessions.get(sessionId);
    const now = Date.now();
    const age = Math.floor((now - session.createdAt) / 1000 / 60); // 分钟

    res.json({
      sessionId,
      userInfo: session.userInfo,
      ageInMinutes: age,
      status: 'active'
    });
  } catch (error) {
    console.error('Failed to get session status:', error);
    res.status(500).json({ error: 'Failed to get session status' });
  }
});

// 关闭会话
app.delete('/api/agent/sessions/:sessionId', async (req, res) => {
  try {
    const { sessionId } = req.params;

    if (!sessions.has(sessionId)) {
      return res.status(404).json({ error: 'Session not found' });
    }

    const session = sessions.get(sessionId);
    await session.context.close();
    await session.browser.close();
    sessions.delete(sessionId);

    res.json({ success: true, message: 'Session closed successfully' });
  } catch (error) {
    console.error('Failed to close session:', error);
    res.status(500).json({ error: 'Failed to close session' });
  }
});

// 健康检查端点
app.get('/api/agent/health', (req, res) => {
  res.json({
    status: 'healthy',
    timestamp: new Date().toISOString(),
    activeSessions: sessions.size,
    llmServiceReady: !!llmService
  });
});

// 清理过期会话
function cleanupSessions() {
  const now = Date.now();
  const SESSION_TIMEOUT = 3600000; // 1小时

  for (const [sessionId, session] of sessions.entries()) {
    if (now - session.createdAt > SESSION_TIMEOUT) {
      session.context.close().catch(console.error);
      session.browser.close().catch(console.error);
      sessions.delete(sessionId);
      console.log(`清理过期会话: ${sessionId}`);
    }
  }
}

// 定期清理会话
setInterval(cleanupSessions, 60000); // 每分钟清理一次

// 启动服务器
app.listen(PORT, () => {
  console.log(`Enhanced Agent server running on port ${PORT}`);
  console.log(`访问 http://localhost:${PORT}/api/agent/health 检查服务状态`);
  console.log(`智能助手增强功能已启用:`);
  console.log(`• DOM结构分析`);
  console.log(`• LLM智能指令理解`);
  console.log(`• 🎥 可视化浏览器自动化操作 (headless: false)`);
  console.log(`• 详细分析结果展示`);
  console.log(`\n💡 浏览器操作现在可见！每个操作间隔1-2秒便于观察`);
});

// 处理进程终止
process.on('SIGINT', async () => {
  console.log('Shutting down enhanced agent server...');

  // 关闭所有会话
  for (const session of sessions.values()) {
    await session.context.close().catch(console.error);
    await session.browser.close().catch(console.error);
  }

  process.exit(0);
});